<template>
  <!-- 指标组件 -->
  <div class="lineChart" v-loading="loading">
    <div class="lineChart-title">
      <!-- <span>折线图</span> -->
      <span>{{ chartName }}</span>
    </div>
    <div class="lineChart-date">
      <div class="">
        <!-- 日期 -->
        <p v-if="screenTime && screenTime.length != 0">
          <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new
            Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
        </p>
        <!-- el-tooltip -->
        <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
          <el-tooltip content="筛选时段" placement="bottom" effect="light">
            <img class="right" :src="dateIcon" alt="">
          </el-tooltip>
        </p>
      </div>

      <!-- select -->
      <el-select v-if="options.length != 0" v-model="queryConditionVal" clearable placeholder="请选择"
        @change="handleChange">
        <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
    </div>
    <!-- tabs -->
    <!-- <div class="lineChart-tabs" v-if="multipleData && multipleData.length != 0">
      <el-radio-group v-model="radio" size="mini" @change="handleChangeRadio">
        <el-radio-button 
          :label="item.chnVal"
          v-for="(item, index) in multipleData"
          :key="index"
        ></el-radio-button>
      </el-radio-group>
    </div> -->
    <!-- <div style="width: 100%;height: 34px;" v-else></div> -->
    <!-- echarts -->
    <div v-if="payloadData.data && payloadData.data.x && payloadData.data.x.length != 0 && isScreenComplete"
      :id="'lineCharts' + id" class="lineChart-echarts" style="width: 100%;height: 272px;"></div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
    <!-- 数据筛选dialog -->
    <OpenDataScreenDialog v-model:visible="openDataScreenVisible" v-model:dataOptions="dataOptions"
      @handleScreen="handleScreen">
    </OpenDataScreenDialog>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import * as echarts from 'echarts';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  merchantReportQueryData,
  merchantReportQueryCondition
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js'
// 组件
import OpenDataScreenDialog from './openDataScreenDialog.vue';
export default {
  name: 'LineChart',
  components: {
    OpenDataScreenDialog
  },
  props: {
    id: {
      type: Number,
      default: () => {
        return null;
      }
    },
    chartName: {
      type: String,
      default: () => {
        return '';
      }
    }
  },
  inject: ['actId'],
  data() {
    return {
      loading: false,
      dateIcon,
      emptyImg,
      data: {},
      relativelyTimeDeal: null,
      radio: '',
      payloadData: {},
      multipleData: [],
      openDataScreenVisible: false,
      dataOptions: [],
      xAxisData: [],
      isScreenComplete: true,
      queryConditionVal: '',
      queryConditionKey: '',
      options: []
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.merchantReportQueryDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
      },
      deep: true
    },
    openDataScreen: {
      handler(val) {
        if (val === this.id) {
          this.openDataScreenVisible = true
        }
      },
      deep: true
    }
  },
  mounted() {
    this.merchantReportQueryConditionApi();
  },
  methods: {
    handleChange(val) {
      this.merchantReportQueryDataApi();
    },
    // 获取条件切换接口
    async merchantReportQueryConditionApi() {
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let res = await merchantReportQueryCondition({
        startTime,
        endTime,
        chartType: 1,
        toIndex: 10,
        beanName: this.id,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      })
      this.options = []
      if (res.code === 200) {
        if (res.payload.length != 0) {
          res.payload.forEach(item => {
            this.options.push(...item.options)
          })
          this.queryConditionVal = this.options[0].value || '';
          this.queryConditionKey = res.payload[0].key || '';
        }
        this.merchantReportQueryDataApi();
      }
    },
    // 筛选数据
    handleScreen(val) {
      this.isScreenComplete = false;
      let legendData = [];
      val.forEach(item => {
        legendData.push(item.name);
      })
      // 通过事件循环极致更新视图
      setTimeout(() => {
        this.isScreenComplete = true;
        // 再次更新界面图表
        this.$nextTick(() => {
          this.drawCharts(this.xAxisData, legendData, val);
        })
      }, 10)
    },
    // 切换tabs
    handleChangeRadio(val) {
      console.log(val, this.multipleData)
      this.multipleData.forEach((item, index) => {
        this.capsulationDealData(index);
      })
    },
    // 获取报表数据
    async merchantReportQueryDataApi() {
      this.loading = true;
      // screenTime为菜单筛选时间
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let paramStr = {
        startTime,
        endTime,
        chartType: 1,
        toIndex: null,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      }
      paramStr[this.queryConditionKey] = this.queryConditionVal;
      const obj=store.state.user.queryConditionObj
      store.commit('SETQUERYCONDITIONOBJ', {...obj,[`${this.id}Key`]:this.queryConditionVal})
      paramStr = JSON.stringify(paramStr);
      let res = await merchantReportQueryData({
        beanName: this.id,
        param: paramStr
      })
      // let res = await merchantReportQueryData({
      //   "beanName":"activityInfoProvider",
      //   "param":"{\"startTime\":1665158400000,\"endTime\":1670464681057,\"field\":\"visitPV\",\"chartType\":1,\"actId\":304,\"insId\":57}"
      // })
      if (res.code === 200) {
        this.payloadData = res.payload;
        this.capsulationDealData()
      }
      this.loading = false;
    },
    capsulationDealData(currentIndex) {
      let valueData = this.payloadData.data;
      if (!valueData) {
        return false;
      }
      this.multipleData = [];
      // 处理数据
      // this.payloadData.forEach((item, index) => {
      //   let obj = {
      //     chnVal: '',
      //     key: index
      //   }
      //   obj.chnVal = item.groupName;
      //   this.multipleData.push(obj);
      // })
      // this.radio = this.multipleData[currentIndex].chnVal;
      // 按照图表处理数据
      let legendData = [];
      let xAxisData = [];
      let seriesData = [];
      xAxisData = valueData.x;
      valueData.y.forEach((item, index) => {
        if (index === 0) {
          item.forEach(value => {
            legendData.push(value.name)
          })
        }
      })
      legendData.forEach(item => {
        let obj = {
          name: item,
          type: 'line',
          showSymbol: false,
          data: []
        }
        valueData.y.forEach(val1 => {
          val1.forEach(val2 => {
            if (item === val2.name) {
              obj.data.push(val2.val)
            }
          })
        })
        seriesData.push(obj);
      })
      console.log('legendData', legendData)
      console.log('xAxisData', xAxisData)
      console.log('seriesData', seriesData)
      this.loading = false;
      this.$nextTick(() => {
        if (xAxisData && xAxisData.length != 0) {
          this.drawCharts(xAxisData, legendData, seriesData);
          console.log('drawCharts', xAxisData, legendData, seriesData);
          this.xAxisData = xAxisData;
          // 数据筛选数据源
          this.dataOptions = seriesData;
        }
      })
    },
    // drawCharts
    drawCharts(xAxisData, legendData, seriesData) {
      let myChart = echarts.init(document.getElementById('lineCharts' + this.id));
      //清除残留数据
      myChart.clear()

      let option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: legendData,
          top: '5%'
        },
        xAxis: {
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '3%',
          containLabel: true
        },
        series: seriesData
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (myChart) myChart.resize();
      })
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    },
    openDataScreen() {
      return store.state.user.openDataScreen;
    }
  }
}
</script>

<style lang="scss" scoped>
.lineChart {
  width: 100%;
  height: 100%;

  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }

  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // margin-bottom: 34px;
    &-div {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .left {
      font-size: 12px;
      color: #6b798e;
    }

    .right {
      margin-left: 18px;
    }

    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  &-tabs {
    width: 100%;
    height: 34px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  &-echarts {
    width: 100%;
    height: 42px;

  }
}
</style>

<style lang="scss">
.lineChart {
  .el-radio-button__inner {
    padding: 6px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}
</style>